var menuLength = getLength("config_page_size");
// jQuery Datatable 对象
var searchTable;
var searchTableForPartner;
var searchOrgTable;
// 组织及角色信息
var checkAccount = false;
var orgTree;
// 后面构建btn 代码
var btnModel = '    \
	{{#each func}}\
    <button type="button" class="{{this.type}} btn-sm" onclick="{{this.fn}}">{{this.name}}</button>\
    {{/each}}';
var template = Handlebars.compile(btnModel);
;(function ($) {
    $.fn.bootstrapValidator.validators.loginNameCheck = {
        html5Attributes: {
            message: 'message',
            field: 'field'
        },
        validate: function (validator, $field, options) {
            return true;
        }
    };
}(window.jQuery));
//输入校验条件
var validator = {
    message: '请核对此字段的输入',
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    submitHandler: function (validator, form, submitButton) {
        var name = submitButton.attr("name");
        var kind =submitButton.attr("data-kind");
        if (name == "saveBtn") {
            saveStaff(kind);
        }
        if (name == "updateBtn") {
            updateSysStaff(kind);
        }
    },
    fields: {
        loginName: {
            validators: {
                notEmpty: {message: '请输入账号'},
                stringLength: {min: 0, max: 20, message: '请输入不超过20个字符'},
                regexp: {regexp: /^[a-zA-Z0-9_\-\.]+$/, message: '用户名由数字字母-_和.组成'},
                loginNameCheck: {message: '账号已经被占用'}
            }
        },
        passwd: {
            validators: {
                notEmpty: {message: '请输入密码'},
                stringLength: {min: 3, max: 20, message: '请输入3~20个字符'}
            }
        },
        staffName: {
            validators: {
                notEmpty: {message: '请输入人员姓名'},
                stringLength: {min: 0, max: 15, message: '请输入不超过15个字'}
            }
        },
        orgName: {
            validators: {
                notEmpty: {message: '请选择所属组织'}
            }
        },
        mobilPhone: {
            validators: {
                notEmpty: {message: '请输入手机号'},
                stringLength: {min: 11, max: 11, message: '请输入11位手机号码'}
            }
        },
        unitName:{
        	validators: {
                notEmpty: {message: '请选择单位'}
            }
        },
        deptName:{
        	validators: {
                notEmpty: {message: '请选择部门'}
            }
        },
        staffLinkId:{
        	validators: {
                notEmpty: {message: '请选择唯一领导'}
            }
        },
        policeFile:{
        	validators: {
                notEmpty: {message: '请上传警官证'}
            }
        }
    }
};
//数据表格的配置（甲方表格）
var tableOption = {
    "ordering": false,// 排序
    "serverSide": true,// 开启服务器模式
    scrollX: true,
    fixedColumns: {
        leftColumns: 0
    },
    lengthMenu: [
        menuLength,
        menuLength
    ],
    ajax: {
        "type": "POST",
        "url": '../staffForPolice/searchMap4Page',//请求路径
        "contentType": 'application/x-www-form-urlencoded; charset=UTF-8',
        "dataType": 'json',
        "data": function (d) {// 查询参数
            d.staffName = $('#searchStaffName').val();
            d.loginName = $('#searchLoginName').val();
            d.orgId = $('#searchOrgId').val();
            d.attrc = $('#searchStaffOrgStatus').val();
            d.staffKind = 1;
            return d;
        }
    },
    columns: [// 对应列
        {
            "data": "staffName", "title": "人员姓名", className: "text-center", render: function (a, b, c, d) {
            return "<a href=\"javascript:doDetail('" + c.staffId + "')\">" + a + "</a>";
        }
        },
        {"data": "loginName", "title": "账号", width: "120", className: "text-center"},
        {"data": "orgName", "title": "所属组织", className: "text-center"},
        {
            "data": "sex", "title": "性别", className: "text-center", render: function (a, b, c, d) {
            return c.sex == 'M' ? '男' : '女';
        }
        },
        {"data": "mobilPhone", "title": "手机号码", width: "120", className: "text-center"},
        {
            "data": "staffOrgStatus", "title": "状态", className: "text-center", render: function (a, b, c, d) {
            if ('1' == a)return '有效'; else return '无效';
        }
        },
        {"data": "staffOrgId", "title": "id", "visible": false},
        {
            "data": null, "title": "操作", className: "text-center", render: function (a, b, c, d) {
            var btnArray = new Array();
            if (hadPermission.update) {
                btnArray.push({"name": "修改", "fn": "showEditPage(\'" + c.staffId + "\')", "type": "user-button"});
            }
            if (hadPermission.update ) {
                btnArray.push({
                    "name": "角色管理",
                    "fn": "addRoleX('" + c.staffOrgId + "','" + c.staffName + "','" + c.orgName + "')",
                    "type": "user-button"
                });
            }
            /*
             if(hadPermission.update){
             btnArray.push({"name":"岗位管理","fn":"orgManage('"+c.staffId+"','"+c.staffName+"','"+c.orgName+"')","type":"user-button"});
             }*/
            if (hadPermission.update) {
                btnArray.push({
                    "name": "密码重置",
                    "fn": "resetPasswd('" + c.staffId + "\',\'" + c.staffName + "\')",
                    "type": "user-button"
                });
            }
            if (hadPermission.del ) {
                //btnArray.push({"name": "删除", "fn": "del(\'" + c.staffId + "\',\'" + c.staffName + "\')", "type": "user-button user-btn-n"});
                if (c.staffOrgStatus == '1') {
                    btnArray.push({
                        "name": "禁用",
                        "fn": "changeStaffOrgStatus(\'" + c.staffOrgId + "\',\'" + c.staffName + "\',\'" + c.orgName + "\',\'0\')",
                        "type": "user-button user-btn-n"
                    });
                } else {
                    btnArray.push({
                        "name": "启用",
                        "fn": "changeStaffOrgStatus(\'" + c.staffOrgId + "\',\'" + c.staffName + "\',\'" + c.orgName + "\',\'1\')",
                        "type": "user-button"
                    });
                }
            }
            context = {
                func: btnArray
            }
            var html = template(context);
            return html;
        }
        }
    ],
    "columnDefs": [
        {// 所有列默认值
            "targets": "_all",
            "defaultContent": '',
            render: $.fn.dataTable.render.ellipsis(22, true)
        }],
    "dom": 'rt<"pull-left mt5"l><"pull-left mt5"i><"pull-right mt5"p><"clear">' //生成样式
};
// 初始化页面
function initFrame() {
    checkAccount = false;
    $('#saveBtn').hide();
    $('#updateBtn').hide();
    $("#orgContainer").hide();
    $('#sysStaffObjectForm input').val('');
    if ($("#partner").hasClass("active")) {//如果当前是乙方标签页激活中
        searchTableForPartner.ajax.reload();
        return;
    }
    searchTable.ajax.reload();
    $('#sysStaffObjectForm').bootstrapValidator('resetForm', true);
}

// 展示查询页面
function staffSearch() {
    $('#statusStaffObjdiv').hide();
    $('#staffContainer').hide();
    $('#myTabContent').show();
    $('#faDIV').hide();
    initFrame();
}

// 查询
function search4Page(staffKind) {
	// 1.警方 2.运维 3.联通
	if (2 === staffKind) {
		$("#searchTableForPartner").DataTable().draw(false);
	} else if (3 == staffKind) {
		$("#searchTableForUnicom").DataTable().draw(false);
	} else {
		$("#searchTable").DataTable().draw(false);
	}
}

// 展示添加页面
function showAddPage(staffKind) {
    $(".staffList").hide();
	validator.fields.passwd.validators = {
			notEmpty : { message : '请输入密码' },
			stringLength: { min: 3, max: 20, message: '请输入3~20个字符' }
	};
	if(1 == staffKind){
		validator.fields.policeFile.validators = {notEmpty: {message: '请上传警官证'}};
	}
    $("#kind" + staffKind).show();
    clearForm($("#editForm" + staffKind));
    $("#polciePhoto").attr("src","");
    $("#editForm" + staffKind).bootstrapValidator(validator);
    $("#editForm" + staffKind).bootstrapValidator('resetForm', true);
    $("button[name='saveBtn']").show();
    $("button[name='updateBtn']").hide();
}
function back(kind){
    $(".kind").hide();
    $(".staffList").show();
    search4Page(kind);
}
function clearForm(objE){//objE为form表单  
    $(objE).find(':input').each(  
        function(){  
            switch(this.type){  
                case 'passsword':  
                case 'select-multiple':  
                case 'select-one':  
                case 'text':  
                case 'textarea':  
                    $(this).val('');  
                    break;  
                case 'checkbox':  
                case 'radio':  
                    this.checked = false;  
            }  
        }     
    );  
}  
//设置树参数
var settingTree = {
    data: {
        key: {
            name: "name"
        },
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pId"
        }
    },
    callback: {
        beforeClick: function (treeId, treeNode) {
        }
    },
    async: {
        enable: true,
        url: "../sysOrgController/loadOrgTreeData",
        autoParam: ["id=pid"]
    }
};
//展示添加表单组织树
function selectTree(yourOrgFunForAdd) {
    var staffKind = $("#staffKindStaffObj").val();
    var disId = $("#disId").val();
    if (staffKind == 1) {
        showTree($("#orgName"), $("#faDIV"));
    } else {
        showOrgTreeForPartnerForAdd(disId, 'yourOrgFunForAdd');
    }

}
//展示甲方查询条件组织树
function showOrgTreeForHome() {
    showTree($("#searchOrgName"), $("#searchHomeOrgDIV"));
}
//展示乙方查询条件组织树
function showOrgTreeForPartner(disId, yourOrgFun) {
//	showTree($("#searchPartnerOrgName"),$("#searchPartnerOrgDIV"));
    var frameSrc = prc + "/sysOrgController/toPartnerOrgList" + "?disId=" + disId + "&yourFun=" + yourOrgFun;
    $("#NoPermissioniframe").attr("src", frameSrc);
    $('#NoPermissionModal').modal({show: true, backdrop: 'static'});
}
function showOrgTreeForPartnerForAdd(disId, yourOrgFunForAdd) {
    var frameSrc = prc + "/sysOrgController/toPartnerOrgList" + "?disId=" + disId + "&yourFun=" + yourOrgFunForAdd;
    $("#NoPermissioniframe").attr("src", frameSrc);
    $('#NoPermissionModal').modal({show: true, backdrop: 'static'});
}
function yourOrgFun(orgId, orgName, orgCode) {
    //alert("orgId=" + orgId + ",orgName=" + orgName + ",orgCode=" + orgCode);
    $("#searchPartnerOrgName").val(orgName);
    $("#searchPartnerOrgId").val(orgId);
    $('#NoPermissionModal').modal("hide");
}
function yourOrgFunForAdd(orgId, orgName, orgCode) {
    $("#orgName").val(orgName);
    $("#orgId").val(orgId);
    if ($('#sysStaffObjectForm').data('bootstrapValidator')) {
        $('#sysStaffObjectForm').data('bootstrapValidator').updateStatus('orgName', 'NOT_VALIDATED', null).validateField('orgName');
    }
    $('#NoPermissionModal').modal("hide");
}
//初始化树的公共方法，需要涉及赋值的name、id对象，和树对象
function initTree(nameObj, idObj, treeId) {
    settingTree.callback.beforeClick = function (treeId, treeNode) {
        $(nameObj).val(treeNode.name);
        //显式重置所属组织的验证标记
        if ($('#sysStaffObjectForm').data('bootstrapValidator')) {
            $('#sysStaffObjectForm').data('bootstrapValidator').updateStatus('orgName', 'NOT_VALIDATED', null).validateField('orgName');
        }
        $(idObj).val(treeNode.id);
    }
    //加载添加表单中的所属组织
    $.fn.zTree.init($(treeId), settingTree, treeArray);
}
//展示树的公共方法，需要传递 name的input对象,用于显示的div对象
function showTree(nameObj, divId) {
    var parentObj = $(nameObj);
    var parentOffset = $(nameObj).offset();
    $(divId).css({
        left: parentOffset.left + "px",
        top: parentOffset.top + parentObj.outerHeight() + "px"
    }).slideDown("fast");
}
//绑定消除树事件
$("html").bind("mousedown", {view: this}, function (event) {
    if (!(event.target.id == "faDIV" || $(event.target).parents("#faDIV").length > 0)) {
        $("#faDIV").fadeOut("fast");
    }
    if (!(event.target.id == "searchHomeOrgDIV" || $(event.target).parents("#searchHomeOrgDIV").length > 0)) {
        $("#searchHomeOrgDIV").fadeOut("fast");
    }
    if (!(event.target.id == "searchPartnerOrgDIV" || $(event.target).parents("#searchPartnerOrgDIV").length > 0)) {
        $("#searchPartnerOrgDIV").fadeOut("fast");
    }
});


//公安版本新增人员信息
function saveStaff(staffKind){
    $(function(){
        //异步提交表单
        $("#editForm"+ staffKind).ajaxSubmit({
            type:'post',
            dataType:'text',
            timeout:100000,
            resetForm: true,
            url:prc+"/staffForPolice/saveStaff.action?t="+(new Date().getTime()),
            success:function(tt){
            	alertModel("新增人员成功");
            	back(staffKind);
            },
            error:function(XmlHttpRequest,textStatus,errorThrown){
            	alertModel("新增人员失败");
            }
        }).submit(function(){return false;});//防止提交后跳转页面
    });

}

// 修改信息展示
function showEditPage(id) {
    $.post('searchStaffMapById.action', {'id': id}, function (data) {
		validator.fields.passwd.validators = {
			stringLength: { min: 3, max: 20, message: '请输入3~20个字符' }
		};
		if(validator.fields.policeFile){
			validator.fields.policeFile.validators = {};
		}
		var sysStaff = data.staffInfo;
	    $(".staffList").hide();
	    $("#kind" + sysStaff.staffKind).show();
	    if (sysStaff.staffKind==1) {
			$(".photo").show();
	    	$("#polciePhoto").attr("src","../staffForPolice/getPhoto?staffId="+id+"&t="+(new Date().getTime()));
	    	$("#polciePhoto").show();
		}else{
			$(".photo").hide();
		}
	    $("#editForm" + sysStaff.staffKind).bootstrapValidator(validator);
	    $("#editForm" + sysStaff.staffKind).bootstrapValidator('resetForm', true);
	    $("button[name='updateBtn']").show();
	    $("button[name='saveBtn']").hide();
	    for (var col in sysStaff) {
	    	if(col == 'passwd'||col == 'updateTime'||col == 'updateBy'){
	    		continue;
			}else if(col == 'orgId'){
	    		$('#kind'+sysStaff.staffKind).find("input[name='orgId']").val(sysStaff.orgId);
	    		$('#kind'+sysStaff.staffKind).find("input[name='deptName']").val(sysStaff.orgName);
	    		$('#kind'+sysStaff.staffKind).find("input[name='unitName']").val(sysStaff.unitName);
	    		$("#policeUnitId").val(sysStaff.unitId);
	    		$('#kind'+sysStaff.staffKind).find("input[name='city1']").val(sysStaff.cityName);
	    		$('#kind'+sysStaff.staffKind).find("input[name='province1']").val(sysStaff.provinceName);
			}else if(col == 'personType'){
	    		$('#kind'+sysStaff.staffKind).find("input[name='personType'][value='"+sysStaff.personType+"']").attr("checked","checked");
			}else if(col == 'officerId'){
				$('#policeLeader').val(sysStaff.officerName);
				$('#policeLeaderId').val(sysStaff.officerId);
			}else if(col == 'sex'){
	    		$('#kind'+sysStaff.staffKind).find("select[name='sex']").val(sysStaff.sex);
			}
			$('#kind'+sysStaff.staffKind).find("input[name='"+col+"']").val(sysStaff[col]);
			
        }
    });
}

//判断账号是否已存在
function checkAccountFun(obj) {
    var loginName = $(obj).val();
    var kind = $(obj).attr("data-kind");
    if ('' == loginName) {
        return;
    }
    $.post('searchOnlyAccount.action?temp=' + (new Date().getTime()), {'loginName': loginName}, function (data) {
        if ('' == data) {
            checkAccount = true;
        } else {
                $('#editForm'+kind)
                    .data('bootstrapValidator')
                    .updateStatus('loginName', 'INVALID','loginNameCheck');
        }
    });
}

// 更新人员及岗位信息
function updateSysStaff(staffKind) {
    confirmModel("确认修改人员信息？", function () {
        $('#_frm_confirm_modal').modal('hide');
    	//异步提交表单
        $("#editForm"+ staffKind).ajaxSubmit({
            type:'post',
            dataType:'text',
            timeout:100000,
            resetForm: true,
            url:prc+"/staffForPolice/updateGacxStaff.action?t="+(new Date().getTime()),
            success:function(tt){
            	alertModel("编辑人员成功");
            	back(staffKind);
            },
            error:function(XmlHttpRequest,textStatus,errorThrown){
            	alertModel("编辑人员失败");
            }
        }).submit(function(){return false;});//防止提交后跳转页面
    });
}


//密码重置
function resetPasswd(id, name) {
    confirmModel('确定重置' + name + '的密码吗?', function () {
        $('#_frm_confirm_modal').modal('hide');
        $.ajax({
            url: "updateForResetPasswd.action",
            cache: false,
            data: {staffId: id},
            dataType: "text",
            type: "POST",
            success: function (data) {
                if (data) {
                    alertModel("用户" + name + "的密码重置成功，新密码为" + data);
                } else {
                    alertModel("密码重置失败！");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alertModel("密码重置时异常：" + errorThrown);
            }
        });
    });
}

//展示人员信息
function doDetail(staffId) {
    var url = prc + "/sysStaffController/goStaffInfo?staffId=" + staffId;
    $("#jump_url").attr("src", url);
    $('#infoModal').modal({
        'show': true
    });
}
/**
 * 修改岗位状态
 * @param record
 * @param status
 */
function changeStaffOrgStatus(staffOrgId, staffName, orgName, status) {
    if ('1' === status) {
        confirmModel("确认恢复" + staffName + "吗？", doChangeStaffOrgStatus, [staffOrgId, status]);
        return;
    }
    confirmModel("确认禁用" + staffName + "吗？", doChangeStaffOrgStatus, [staffOrgId, status]);
}
function doChangeStaffOrgStatus(array) {
    $.post('doChangeStaffOrgStatus', {"staffOrgId": array[0], "status": array[1]}, function (result) {
        if (result.flag === 'success') {
            if (array[1] === '0') {
                alertModel("禁用成功");
            } else {
                alertModel("恢复成功");
            }
            if ($("#partner").hasClass("active")) {//如果当前是乙方标签页激活中
                search4Page(2);
                return;
            }
            search4Page(1);
        } else {
            if (array[1] === '1') {
                alertModel("禁用失败");
            } else {
                alertModel("恢复失败");
            }
        }
    });
}
//岗位的角色设置
function addRoleX(staffOrgId, staffName, orgName) {
//	var url = "goSysOrgAndRoleShow.action?id="+id;
//	window.open(url,'',"height=500px,width=1000px,toolbar=no,resizable=yes,location=no,top=150,left=200");
    $("#selectedStaffOrg").html(staffName + " " + orgName);
    $("#selectedStaffRoleId").val(staffOrgId);
    $("#hadRoles").empty();
    $("#notHavingRoles").empty();
    $.post('searchRolesByStaffOrgId', {staffOrgId: staffOrgId}, function (array) {
        var hadRoles = array.hadRoles;
        var notHavingRoles = array.notHavingRoles;
        for (var i = 0; i < hadRoles.length; i++) {
            $("#hadRoles").append($("<option value=\"" + hadRoles[i].ID + "\">" + hadRoles[i].NAME + "</option>"));
        }
        for (var i = 0; i < notHavingRoles.length; i++) {
            $("#notHavingRoles").append($("<option value=\"" + notHavingRoles[i].ID + "\">" + notHavingRoles[i].NAME + "</option>"));
        }
        //初始化左右选择控件
        $('#notHavingRoles').multiselect({
            keepRenderingSort: true,
            right: '#hadRoles',
            rightAll: '#rightAll',
            rightSelected: '#rightSelected',
            leftSelected: '#leftSelected',
            leftAll: '#leftAll',
            search: {
                left: '<input type="text" name="q" class="form-control" style="margin-bottom:10px" placeholder="查询待选..." />',
                right: '<input type="text" name="q" class="form-control" style="margin-bottom:10px" placeholder="查询已选..." />',
            },
            fireSearch: function (value) {
                return value.length > 0;
            }
        });
    });
//	$('#rolesModal').modal({'show':true});
    $(".roleSetting").show();
    $(".staffList").hide();
}
//保存岗位角色设置
function doSaveRoles() {
    var all = "";
    $("#hadRoles option").each(function () {
        all += $(this).attr("value") + ",";
    });
    $.post('saveRolesToStaffOrgId', {roles: all, staffOrgId: $("#selectedStaffRoleId").val()}, function (result) {
        if (result.flag === 'success') {
            //$('#rolesModal').modal('hide');
            alertModel("保存成功");
            $(".roleSetting").hide();
            $(".staffList").show();
        }
    });
}
function showList() {
    $(".staffUpdate").hide();
    $(".roleSetting").hide();
    $(".staffList").show();
    $("#orgContainer").hide();
}

$(function () {
    $("input[name='loginName']").blur(function () {
        checkAccountFun(this)
    });
    //为了防止页面大小改变后，隐藏的表格变形，再每次标签页显示后，都重新绘制表格
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        if ("operationAnchor" === e.target.id) {
            searchTableForPartner.draw(false);
        } else if ("policeAnchor" === e.target.id) {
            searchTable.draw(false);
        } else {
            searchTableForUnicom.draw(false);
        }
    });
    if ("1" == $("#currentStaffKind").val()) {//如果是警方人员，查看警方信息
        $('#operationAnchor').hide();
        // 警方表格
        searchTable = $("#searchTable").DataTable(tableOption);
    } else if ("4" == $("#currentStaffKind").val()) {//如果是超级管理员，全部可看
        $('#operationAnchor').one("click", function () {
            // 运维表格
            var partnerTableOption = tableOption;//复制甲方表格配置，修改其中的查询参数
            partnerTableOption.ajax.data = function (d) {// 查询参数
                d.staffName = $('#searchPartnerName').val();
                d.loginName = $('#searchPartnerLoginName').val();
                d.orgId = $('#searchPartnerOrgId').val();
                d.attrc = $('#searchPartnerStaffOrgStatus').val();
                d.staffKind = 2;
                return d;
            };
            searchTableForPartner = $("#searchTableForPartner").DataTable(partnerTableOption);
        });
        $('#unicomAnchor').one("click", function () {
            // 联通表格
            var unicomTableOption = tableOption;//复制甲方表格配置，修改其中的查询参数
            unicomTableOption.ajax.data = function (d) {// 查询参数
                d.staffName = $('#searchUnicomName').val();
                d.loginName = $('#searchUnicomLoginName').val();
                d.orgId = $('#searchUnicomOrgId').val();
                d.attrc = $('#searchUnicomStaffOrgStatus').val();
                d.staffKind = 3;
                return d;
            };
            searchTableForUnicom = $("#searchTableForUnicom").DataTable(unicomTableOption);
        });
        searchTable = $("#searchTable").DataTable(tableOption);
    } else {
        $("#searchTable").hide()
        // 运维表格
        var partnerTableOption = $(tableOption).clone();//复制警方表格配置，修改其中的查询参数
        partnerTableOption.ajax.data = function (d) {// 查询参数
            d.staffName = $('#searchPartnerName').val();
            d.loginName = $('#searchPartnerLoginName').val();
            d.orgId = $('#searchPartnerOrgId').val();
            d.attrc = $('#searchPartnerStaffOrgStatus').val();
            d.staffKind = 2;
            return d;
        };
        searchTableForPartner = $("#searchTableForPartner").DataTable(partnerTableOption);
        $('#unicomAnchor').one("click", function () {
            // 联通表格
            var unicomTableOption = $(tableOption).clone();//复制甲方表格配置，修改其中的查询参数
            unicomTableOption.ajax.data = function (d) {// 查询参数
                d.staffName = $('#searchPartnerName').val();
                d.loginName = $('#searchPartnerLoginName').val();
                d.orgId = $('#searchPartnerOrgId').val();
                d.attrc = $('#searchPartnerStaffOrgStatus').val();
                d.staffKind = 3;
                return d;
            };
            searchTableForPartner = $("#searchTableForUnicom").DataTable(unicomTableOption);
        });
    }
    //初始化三棵树
    initTree($("#orgName"), $("#orgId"), $("#orgTree"));
    initTree($("#searchOrgName"), $("#searchOrgId"), $("#orgHomeTree"));
    initTree($("#searchPartnerOrgName"), $("#searchPartnerOrgId"), $("#orgPartnerTree"));
});
function searchReset() {
    $("#searchOrgId").val("");
}
function searchPartnerReset() {
    $("#searchPartnerOrgId").val("");
}
//人员的岗位管理  hurx
function orgManage(staffId, staffName, orgName) {
    $("#myTabContent").hide();
    $("#orgManageTitle").html(staffName + "的岗位操作");
    $("#orgContainer").show();
    $("#staffId").val(staffId);
    $("#searchOrgTable").DataTable().destroy();
    searchOrgTable = $("#searchOrgTable").DataTable({
        "ordering": false,// 排序
        "serverSide": true,// 开启服务器模式
        "scrollX": true,// 横向滚动
        ajax: {
            "type": "POST",
            "url": 'getStaffOrg.action',//请求路径
            "contentType": 'application/x-www-form-urlencoded; charset=UTF-8',
            "dataType": 'json',
            "data": {"staffId": staffId, "orgId": null}
        },
        columns: [// 对应列
            {"data": null, className: "text-center", visible: false},
            {
                "data": null, className: "text-center", render: function (a, b, c, d) {
                var staffOrgBtnArray = new Array();
                if ('F' == c.staffOrgType) {
                    staffOrgBtnArray.push({
                        "name": "修改",
                        "fn": "showOrgEditPage(\'" + c.staffOrgId + "\',\'" + c.staffOrgType + "\')",
                        "type": "user-button"
                    });
                } else {
                    staffOrgBtnArray.push({
                        "name": "修改",
                        "fn": "showOrgEditPage(\'" + c.staffOrgId + "\',\'" + c.staffOrgType + "\')",
                        "type": "user-button"
                    });
                    staffOrgBtnArray.push({
                        "name": "删除",
                        "fn": "delOrg(\'" + c.staffOrgId + "\',\'" + c.orgName + "\')",
                        "type": "user-button user-btn-n"
                    });
                }
                if (hadPermission.dpmanage) {
                    staffOrgBtnArray.push({
                        "name": "数据权限管理",
                        "fn": "goDP(\'" + c.staffOrgId + "\',\'" + c.staffId + "\',\'" + c.orgId + "\')",
                        "type": "user-button"
                    });
                }
                var context =
                {
                    func: staffOrgBtnArray
                };
                var html = template(context);
                return html;
            }
            },
            {
                "data": "staffOrgType", className: "text-center", render: function (a, b, c, d) {
                if ('F' == c.staffOrgType) {
                    return '主岗';
                } else if ('T' == c.staffOrgType) {
                    return '兼职';
                } else {
                    return '借调';
                }
            }
            },
            {"data": "orgName", className: "text-center"},
            {
                "data": "staffOrgStatus", className: "text-center", render: function (a, b, c, d) {
                if ('1' == c.staffOrgStatus) {
                    return '有效';
                } else {
                    return '无效';
                }
            }
            },
            {"data": "hireDate", className: "text-center"},
            {"data": "effectStartDate", className: "text-center"},
            {"data": "effectEndDate", className: "text-center"},
            {"data": "duty", className: "text-center"},
        ],
        "columnDefs": [
            {// 所有列默认值
                "targets": "_all",
                "defaultContent": ''
            },
        ],
        lengthMenu: [
            [10, 25, 50],
            ['10', '25', '50']
        ],
        "dom": 'lrt<"bottom"ip><"clear">' //生成样式
    });
}
var checkValidator = {
    message: 'This value is not valid',
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        staffOrgName: {
            validators: {
                notEmpty: {
                    message: '请点击选择组织'
                }
            }
        },
        duty: {
            validators: {
                stringLength: {min: 0, max: 100, message: '请输入不超过100个字符'}
            }
        }
    },
    submitHandler: function (validator, form, submitButton) {
        // Use Ajax to submit form data
        if ($(submitButton).attr('id') == 'addOrgBtn') {
            addStaffOrg();
        }
        if ($(submitButton).attr('id') == 'updateOrgBtn') {
            updateStaffOrg();
        }
    }
};
//返回岗位操作list
function showOrg() {
    $("#orgOperation").hide();
    $("#orgContainer").show();
    $("#addBtn").hide();
    $("#orgOperation input").val("");
    $("#orgOperation select option:first").attr("selected", "selected");
    $('#orgForm').bootstrapValidator('resetForm', true);
    orgTree = null;
}
//组织树设置
var orgSetting = {
    view: {
        selectedMulti: false
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "oCode",
            pIdKey: "pCode"
        }
    },
    callback: {
        beforeClick: function (treeId, treeNode) {
            $('#staffOrgOrgId').val(treeNode.id);
            $('#staffOrgName').val(treeNode.name);
            $('#staffOrgName').change();
            $('#staffOrgCloseModal').click();
        }
    },
    async: {
        enable: true,
        url: "../sysOrgController/disOrgTree",
        autoParam: ["oCode", "has_bm", "orgKind"]
    }
};
//展示新增岗位
function showOrgAddPage() {
//	$(".head-title").hide();
    $("#orgContainer").hide();
    $("#orgOperation").show();
    $("#orgOperationTitle").html("新增岗位");
    $("#staffOrgType").show();
    $("#staffOrgTypeForMajor").hide();
    $("#updateOrgBtn").hide();
    $('#addOrgBtn').show();
    $("#staffOrgStatus").show();
    $("#staffOrgStatus1").hide();
    $.post("../sysOrgController/selectorgTree.action", {"oCode": "", "has_bm": "1", "orgKind": "1"}, function (data) {
        orgTree = $.fn.zTree.init($("#staffOrgTree"), orgSetting, data);
    });
    if (null == $('#orgForm').data('bootstrapValidator')) {
        $('#orgForm').bootstrapValidator(checkValidator);
    }
    $('#staffOrgName').on('change', function (e) {
        $('#orgForm')
            .data('bootstrapValidator')
            .updateStatus('staffOrgName', 'NOT_VALIDATED', null)
            .validateField('staffOrgName');

    });
}
//添加岗位
function addStaffOrg() {
    var staffId = $("#staffId").val();
    var orgId = $("#staffOrgOrgId").val();
    var staffOrgType = $("#staffOrgType").val();
    var hireDate = $("#staffOrgHireDate").val();
    var effectStartDate = $("#staffOrgStartDate").val();
    var effectEndDate = $("#staffOrgEndDate").val();
    var staffOrgStatus = $("#staffOrgStatus").val();
    var duty = $("#duty").val();
    $.ajax({
        url: "addStaffOrg.action",
        data: {
            "staffId": staffId,
            "staffOrgType": staffOrgType,
            "orgId": orgId,
            "hireDate": hireDate,
            "effectStartDate": effectStartDate,
            "effectEndDate": effectEndDate,
            "staffOrgStatus": staffOrgStatus,
            "duty": duty
        },
        dataType: "JSON",
        type: "POST",
        success: function (data) {
            showOrg();
            orgTree = null;
            searchOrgTable.ajax.reload();
            alertModel("添加成功！");
        },
        error: function (e) {
            alertModel("添加失败o_o请重试...");
        }
    })
}
//修改岗位
function showOrgEditPage(staffOrgId, staffOrgType) {
//	$(".head-title").hide();
    $("#orgOperationTitle").html("修改岗位");
    $("#orgContainer").hide();
    $("#orgOperation").show();
    $("#addOrgBtn").hide();
    $("#updateOrgBtn").show();
    if (null == $('#orgForm').data('bootstrapValidator')) {
        $('#orgForm').bootstrapValidator(checkValidator);
    }
    $('#staffOrgName').on('change', function (e) {
        $('#orgForm')
            .data('bootstrapValidator')
            .updateStatus('staffOrgName', 'NOT_VALIDATED', null)
            .validateField('staffOrgName');
    });
    $.post("../sysOrgController/selectorgTree.action", {"oCode": "", "has_bm": "1", "orgKind": "1"}, function (data) {
        orgTree = $.fn.zTree.init($("#staffOrgTree"), orgSetting, data);
    });
    $.post("getStaffOrgByStaffOrgId", {"staffOrgId": staffOrgId}, function (data) {
        $("#staffOrgId").val(data.staffOrgId);
        $("#staffId").val(data.staffId);
        $("#staffOrgOrgId").val(data.orgId);
        $("#staffOrgName").val(data.orgName);
        $("#orgType").val(data.staffOrgType);
        if (data.staffOrgType == "F") {
            $("#staffOrgTypeForMajor").show();
            $("#staffOrgTypeForMajor").val("主岗");
            $("#staffOrgType").hide();
            $("#staffOrgStatus1").show();
            $("#staffOrgStatus").hide();
            $("#staffOrgStatus1").val("有效");
        } else {
            if (data.staffOrgType == "T") {
                $("#parttime").attr("selected", "selected");
            } else if (data.staffOrgType == "J") {
                $("#transfer").attr("selected", "selected");
            }
            $("#staffOrgTypeForMajor").hide();
            $('#staffOrgType').show();
            $("#staffOrgStatus").show();
            $("#staffOrgStatus1").hide();
            if (data.staffOrgStatus == "1") {
                $("#inUse").attr("selected", "selected");
            } else if (data.staffOrgStatus == "0") {
                $("#outOfUse").attr("selected", "selected");
            }
        }
        $("#staffOrgHireDate").val(data.hireDate);
        $("#staffOrgStartDate").val(data.effectStartDate);
        $("#staffOrgEndDate").val(data.effectEndDate);
        $("#duty").val(data.duty);
    });
}
function setPoliceUnit(id,name){
	$('#policeUnitId').val(id);
	$('#policeUnit').val(name);
	$('#editForm1').data('bootstrapValidator').updateStatus('unitName', 'VALID', null);
}
//部门
function getDepartment(obj){
	var topId=$('#policeUnitId').val();
	var ob=$(obj);
	selectOrgTree(ob,topId,setPoliceOrgId,0,'1','1',3,100,30);
}
function setPoliceOrgId(id,name){
	$('#policeDepartmentId').val(id);
	$('#policeDepartment').val(name);
	$('#editForm1').data('bootstrapValidator').updateStatus('deptName', 'VALID', null);
}
function setLeader(orgId , orgName, staffOrgId,  staffid , staffName){
	$('#policeLeaderId').val(staffid);
	$('#policeLeader').val(staffName);
	$('#editForm1').data('bootstrapValidator').updateStatus('staffLinkId', 'VALID', null);
}
//运维----
function setOperUnit(id,name){
	$('#operUnitId').val(id);
	$('#operUnit').val(name);
	}
	//部门
function getOperDepartment(obj){
		var topId=$('#operUnitId').val();
		var ob=$(obj);
		selectOrgTree(ob,topId,setOperOrgId,'1','1','1',3,200,300);
}
function setOperOrgId(id,name){
		$('#operDepartmentId').val(id);
		$('#operDepartment').val(name);
	}
//联通-----
function setUnicomUnit(id,name){
	$('#unicomUnitId').val(id);
	$('#unicomUnit').val(name);
	}
	//部门
function getUnicomDepartment(obj){
		var topId=$('#unicomUnitId').val();
		var ob=$(obj);
		selectOrgTree(ob,topId,setUnicomOrgId,'1','1','1',3,200,300);
}
function setUnicomOrgId(id,name){
		$('#unicomDepartmentId').val(id);
		$('#unicomDepartment').val(name);
	}

function updateStaffOrg() {
    var staffOrgId = $("#staffOrgId").val();
    var orgId = $("#staffOrgOrgId").val();
    var hhh = $("#orgType").val();
    if (hhh == "F") {
        var staffOrgType = "F";
        var staffOrgStatus = 1;
    } else {
        var staffOrgType = $("#staffOrgType").val();
        var staffOrgStatus = $("#staffOrgStatus").val();
    }
    var hireDate = $("#staffOrgHireDate").val();
    var effectStartDate = $("#staffOrgStartDate").val();
    var effectEndDate = $("#staffOrgEndDate").val();
    var duty = $("#duty").val();
    $.ajax({
        url: "updateStaffOrg.action",
        data: {
            "staffOrgId": staffOrgId,
            "orgId": orgId,
            "staffOrgType": staffOrgType,
            "hireDate": hireDate,
            "effectStartDate": effectStartDate,
            "effectEndDate": effectEndDate,
            "staffOrgStatus": staffOrgStatus,
            "duty": duty
        },
        dataType: "JSON",
        type: "POST",
        success: function (data) {
            showOrg();
            orgTree = null;
            searchOrgTable.ajax.reload();
            alertModel("更新成功！");
        },
        error: function (e) {
            alertModel("更新失败o_o请重试...");
        }
    })
}
//删除岗位（物理删除）
function delOrg(staffOrgId, orgName) {
    confirmModel("确认删除岗位" + orgName + "么？（永久删除）", function () {
        $.post("delStaffOrg.action", {"staffOrgId": staffOrgId}, function (data) {
            alertModel("删除成功！");
            searchOrgTable.ajax.reload();
        })
    });
}
function goDP(id, staffid, orgid) {
    window.open("../dataPermissionController/goDataPermission?id=" + id + "&staffId=" + staffid + "&orgId=" + orgid);
}


function loadDeferScript() {
    /**修改因为高度问题导致分页下移的问题*/
    if (myBrowser() == "IE9") {
        if ($(".DTFC_LeftHeadWrapper").length > 0 && $(".DTFC_LeftBodyWrapper").length > 0) {
            var needChangeHeight = $("#searchTable_wrapper .DTFC_ScrollWrapper").height();
            $("#searchTable_wrapper .DTFC_ScrollWrapper").height((needChangeHeight - 65) + "px");
        }
    }
}

$(document).on('click', '#searchTable_paginate li.paginate_button a', function () {
    setTimeout("loadDeferScript()", 1000);
});

$(document).on('click', '#searchTableForPartner_paginate li.paginate_button a', function () {
    setTimeout("loadDeferScript()", 1000);
});
$(document).on('click', '#searchOrgTable_paginate li.paginate_button a', function () {
    setTimeout("loadDeferScript()", 1000);
});
